package leetcode;

public class LeetCode34 {

    public int[] searchRange(int[] nums, int target) {
        if (nums.length == 1)
            return nums[0] == target ? new int[]{0, 0} : new int[]{-1, -1};
        int index = binarySearch(target, nums), left = index, right = index;
        if (index == -1)
            return new int[]{-1, -1};
        while (left >= 0 && nums[left] == target) {
            left--;
        }
        while (right < nums.length && nums[right] == target) {
            right++;
        }
        return new int[]{left + 1, right - 1};
    }

    private int binarySearch(int target, int[] nums) {
        int left = 0, right = nums.length - 1, mid;
        while (left <= right) {
            mid = (left + right) / 2;
            if (target == nums[mid])
                return mid;
            else if (target < nums[mid]) {
                right = mid - 1;
            } else
                left = mid + 1;
        }
        return -1;
    }


//------------------------------------------------------------------
}
